from sklearn.feature_extraction.text import HashingVectorizer
import numpy as np
import pickle
import os

# 把输入强转成int型
# 失败则返回0
def to_int(val):
    try:
        return int(val)
    except:
        return 0


# 把输入强壮成float型
# 失败则返回0.0
def to_float(val):
    try:
        return float(val)
    except:
        return 0.0


# 把输入的字符窜转成vector
def to_vector(str_value, n_features=5):
    try:
        vectorizer = HashingVectorizer(n_features=n_features)
        return vectorizer.transform([str_value]).toarray()
    except:
        return np.zeros((1, n_features))

# 保存二进制文件
def save_to_b(file_path, content, force_write=False):
    if is_file_or_directory_exist(file_path) and not force_write:
        return
    else:
        with open(file_path, mode='wb') as f:
            pickle.dump(content, f)

# 读取二进制文件
def load_from_b(file_path):
    with open(file_path, mode='rb') as f:
        return pickle.load(f)

# 判断文件是否存在
def is_file_or_directory_exist(file_path):
    return os.path.exists(file_path)

# 创建文件夹
def create_directory(path):
    if not is_file_or_directory_exist(path):
        os.makedirs(path)